let app = getApp();
import {
  getGoodsInfo,
  getGoodsParameter,
  getGoodsSetmeal,
  checkCollection,
  addCollection,
  delCollectionByGoodsId
} from "../../api";
import {
  getTelePhone
} from "../../api/shop"
const parse = require("../../node_modules/mini-html-parser2");
import {
  disposeData
} from "../../utils/outData";
import {
  baseImgUrl,
  programTitle
} from "../../setting";
Page({
  data: {
    goodsId: '',
    goodsInfo: {},
    swiperList: [],
    isShowParameter: false,
    showBottom: false,
    parameterList: [],
    setmealList: [],
    leaseList: [],
    tabs: [{
        id: 0,
        title: '商品详情'
      },
      {
        id: 1,
        title: '租赁说明'
      }
    ],
    activeTabId: 0,
    curLease: 0,
    curSetmeal: 0,
    nodes: [],
    labelList: [],
    collectShow: false, //收藏红心状态
    rentNum: 1,
    leaseId: '', // 租期id
    huabei_stages: '', // 花呗分期数
    setmealId: '', // 套餐id
    huabeiData: {},
    dayRent: '',
    serviceShow: false,
    shop_mobile: '',
    platform_mobile: '',
    selectedPackage: '',
    quantity: '',
    isloading: true,
    is_renewal: '', //是否续租,
    parent_order_id: '', //原续租订单号,
    relationId: '',
    order_from: '',
    serveList: []
  },
  onLoad(option) {

    // console.log('shezhi', option)
    my.removeStorage({
      key: 'isAuthShow'
    });
    const token = my.getStorageSync({
      key: 'token'
    }).data;
    this.setData({
      goodsId: option.goodsId || disposeData().goodsId,
      order_from: option.from || 'search',
      // setmealId: option.setmealId || '',
      is_renewal: option.is_renewal || '',
      parent_order_id: option.parent_order_id || '',
      relationId: disposeData().relationId || '',
    })
    this.getDetails()

    if (token) {
      this.checkIsCollect()
    }
  },
  onShow(){

  },
  getDetails() {
    this.setData({
      isloading: true
    })
    getGoodsInfo({
      goods_id: this.data.goodsId,
    }).then(res => {
      // console.log('详情', res);
      if (res.length == 0) {
        this.setData({
          goodsInfo: []
        })
      } else {
        let imgs = res.carousel_images
        let imgList = []
        if (imgs && imgs.indexOf(",") == -1) {
          imgList.push(imgs)
        } else {
          imgList = imgs ? imgs.split(',') : []
        }
        let contentHtml = res.goods_content.replace(/<img [^>]*src=['"]([^'"]+)[^>]*>/gi, (match, capture) => {
          let newStr = '<img src="' + capture + '" style="width:100%;" alt="" />';
          return newStr;
        });
        parse(contentHtml, (err, nodes) => {
          if (!err) {
            this.setData({
              nodes: nodes,
            })
          }
        })
        let num=res.rent_label.split(',')
    
        let labelArr = res.rent_label ? res.rent_label.replace(/,/g, '，').split('，').filter((p, idx) => p != '' && idx < num.length) : [];
        this.setData({
          goodsInfo: res,
          labelList: labelArr,
          swiperList: imgList.map(item => ({
            img: item
          })),
          isloading: false,
        })
      }
    })
  },
  checkIsCollect() {
    checkCollection(this.data.goodsId).then(res => {
      this.setData({
        collectShow: res.is_collection == 0 ? false : true
      })
    })
  },
  onParBanner(e) {
    const urls = this.data.swiperList.map(item => baseImgUrl + item.img);
    my.previewImage({
      current: e.index,
      urls: urls
    });
  },
  toComplain() {
    my.navigateTo({
      url: '../complaints/complaints?goodsTitle=' + this.data.goodsInfo.title
    });
  },
  toShare() {
    my.showSharePanel();
  },
  checkParameter() {
    getGoodsParameter(this.data.goodsId).then(res => {
      if (res.length > 0) {
        this.setData({
          isShowParameter: !this.data.isShowParameter,
          parameterList: res
        })
      } else {
        my.showToast({
          type: 'none',
          content: '暂无参数',
          duration: 2000
        });
      }
    })
  },
  onPopupClose() {
    this.setData({
      isShowParameter: false,
      showBottom: false,
    })
  },

  // 优惠券
  getCoupon() {},
  jumpStore() {
    const {
      shopname,
      member_id
    } = this.data.goodsInfo
    my.navigateTo({
      url: '../storeDetails/storeDetails?shopname=' + shopname + "&member_id=" + member_id
    });
  },
  handleTabClick({
    index,
    tabsName
  }) {
    this.setData({
      [tabsName]: index,
    });
  },
  toIndex() {
    my.switchTab({
      url: '../index/index'
    })
  },
  getAuthorize() {

  },
  closeModal() {
    this.setData({
      serviceShow: false
    })
  },
  goService() {
    getTelePhone(this.data.goodsInfo.member_id).then(res => {
      this.setData({
        serviceShow: true,
        shop_mobile: res.shop_mobile,
        platform_mobile: res.platform_mobile
      })
    })
  },
  callPhone(e) {
    const phone = e.currentTarget.dataset.phone;
    if (phone) {
      my.makePhoneCall({
        number: phone
      })
    }
  },
  goToService() {
    my.switchTab({
      url: '../service/service'
    })
  },
  isCollection() {
    const token = my.getStorageSync({
      key: 'token'
    }).data;
    if (token) {
      if (!this.data.collectShow) {
        addCollection(this.data.goodsId).then(res => {
          my.showToast({
            type: 'success',
            content: '收藏成功',
            duration: 1000
          });
          this.setData({
            collectShow: true
          })
        })
      } else {
        delCollectionByGoodsId(this.data.goodsId).then(res => {
          my.showToast({
            type: 'success',
            content: '取消收藏',
            duration: 1000
          });
          this.setData({
            collectShow: false
          })
        })
      }
    } else {
      const that = this
      app.getAuthUser(function (res) {
        if (res) {
          that.checkIsCollect()
        }
      })
    }
  },
  collect() {
    this.isCollection()
  },
  getSetmeal() {
    getGoodsSetmeal(this.data.goodsId).then(res => {
        let service = res[0].service
        let name = service.map((e, index) => {
          return e.service_type
      })
        let nameList = name.map((e, index) => {
          return {
            name:e
          }
        })
        let list = service.map((e) => {
          delete e.service_type
          return Object.keys(e).map((item) => e[item])
        })
        nameList.forEach((e, index) => {
          e.children = list[index]
        })
      this.setData({
        setmealList: res,
        leaseList: res[0].spec,
        huabeiData: res[0].spec[0].huabei_data,
        setmealId: res[0].id,
        leaseId: res[0].spec[0].id,
        dayRent: res[0].spec ? res[0].spec[0].day_price : '',
        firstRent: res[0].spec ? res[0].spec[0].first_rent : '',
        totalRent: res[0].spec ? res[0].spec[0].total_amount : '',
        totalValue: res[0].price,
        quantity: res[0].quantity,
        selectedPackage: res[0].title,
        serveList:nameList
      })
      // if(this.data.setmealId){
      //   this.setData({
      //     setmealId: this.data.setmealId
      //   })
    })
    // }
  },
  toFreeRent() {
    this.getSetmeal()
    this.setData({
      showBottom: !this.data.showBottom,
      huabei_stages: '',
      rentNum: 1,
      curSetmeal: 0,
      curLease: 0
    })
  },
  changeSetmeal(e) {
    const {
      curIndex,
      setmealData
    } = e.currentTarget.dataset
    // console.log('套餐选择',setmealData)
    const {
      curLease
    } = this.data
    this.setData({
      rentNum: 1,
      curSetmeal: curIndex,
      huabei_stages: '',
      huabeiData: {},
      setmealId: setmealData.id,
      leaseId: setmealData.spec[curLease].id,
      leaseList: setmealData.spec,
      //curLease: setmealData.spec[curLease].index,
      dayRent: setmealData.spec ? setmealData.spec[curLease].day_price : '',
      firstRent: setmealData.spec ? setmealData.spec[curLease].first_rent : '',
      totalRent: setmealData.spec ? setmealData.spec[curLease].total_amount : '',
      totalValue: setmealData.price,
      quantity: setmealData.quantity,
      selectedPackage: setmealData.title,
    })
    if (setmealData.spec.length > 0 && setmealData.spec[0].huabei_data) {
      this.setData({
        huabeiData: setmealData.spec[0].huabei_data
      })
    }
  },
  changeLease(e) {
    const {
      leaseIndex,
      huabeiObj,
      leaseTime,
      leaseId
    } = e.currentTarget.dataset
    // console.log('changeLease',leaseIndex, leaseId, leaseTime, huabeiObj)
    if (huabeiObj && huabeiObj.length) {
      huabeiObj.forEach(item => {
        if (leaseTime == item.lease_term) {
          item.three_select = false
          item.six_select = false
          item.twelve_select = false
          this.setData({
            huabeiData: item
          })
        }
      })
    }
    this.data.leaseList.forEach(item => {
      if (leaseId == item.id) {
        this.setData({
          dayRent: item.day_price,
          firstRent: item.first_rent,
          totalRent: item.total_amount
        })
      }
    })
    this.setData({
      curLease: leaseIndex,
      leaseId: leaseId
    })
  },
  changeHuabei(e) {
    let huabei = e.currentTarget.dataset.huabei
    let obj = {
      ...this.data.huabeiData
    }
    // console.log('选择',huabei, obj)
    if (huabei == 3) {
      obj.three_select = !obj.three_select
      obj.six_select = false
      obj.twelve_select = false
    } else if (huabei == 6) {
      obj.three_select = false
      obj.six_select = !obj.six_select
      obj.twelve_select = false
    } else if (huabei == 12) {
      obj.three_select = false
      obj.six_select = false
      obj.twelve_select = !obj.twelve_select
    }
    this.setData({
      huabeiData: obj
    })
    if (!obj.three_select && !obj.six_select && !obj.twelve_select) {
      this.setData({
        huabei_stages: ''
      })
    } else {
      this.setData({
        huabei_stages: huabei
      })
    }
  },
  changeNumber(value) {
    this.setData({
      rentNum: value,
    });
  },
  selectServe(e) {
    const {
     key,id
    } = e.target.dataset

 let list=this.data.serveList

 list[key].children.forEach((e)=>{
      if(e.id==id){
        e.is_show =!e.is_show
      }else{
        e.is_show=false
      }
  })
    this.setData({
      serveList:list
    })
  },
  goBuy() {
    const that = this
    let serveid=[]
    const token = my.getStorageSync({
      key: 'token'
    }).data;
    const {
      goodsInfo,
      goodsId,
      setmealId,
      leaseId,
      rentNum,
      huabei_stages,
      quantity,
      is_renewal,
      relationId,
      parent_order_id,
      order_from,
      serveList
    } = that.data;
    if (serveList != undefined) {
      serveList.forEach((item) => {
        item.children.forEach((child) => {
            if (child.is_show) {
              serveid.push(child.id);
            }
        });
    });
    }
    if (quantity < 1) {
      my.showToast({
        type: 'none',
        content: '库存不足',
        duration: 1500,
      });
      return
    }
    if (token) {
      my.navigateTo({
        url: '../makeOrder/makeOrder?goodsId=' + goodsId + "&setmealId=" + setmealId + "&leaseId=" + leaseId + '&parent_order_id=' + parent_order_id +
          "&num=" + rentNum + "&isShow=" + goodsInfo.is_show + "&huabei_stages=" + huabei_stages + "&isRenewal=" + is_renewal + '&relationId=' + relationId + '&from=' + order_from + '&serveid=' + serveid

      });
      this.setData({
        showBottom: false
      })
    } else {
      app.getAuthUser(function (res) {
        if (res) {
          my.navigateTo({
            url: '../makeOrder/makeOrder?goodsId=' + goodsId + "&setmealId=" + setmealId + "&leaseId=" + leaseId + '&parent_order_id=' + parent_order_id + "&num=" + rentNum + "&isShow=" + goodsInfo.is_show + "&huabei_stages=" + huabei_stages + "&isRenewal=" + is_renewal + '&relationId=' + relationId + '&from=' + order_from + '&serveid=' + serveid
          });
          that.setData({
            showBottom: false
          })
        }
      })
    }
  },
  onShareAppMessage() {
    // 返回自定义分享信息
    return {
      title: this.data.goodsInfo.title,
      desc: this.data.goodsInfo.spread_title,
      searchTip: programTitle,
      content: '选择' + programTitle + '，生活没烦恼',
      path: 'pages/productDetails/productDetails?from=qrcode&goodsId=' + this.data.goodsId,
    };
  }
});